import router from "@/router";
import store from "@/store";
import ACCESS_ENUM from "@/access/accessEnum";
import checkAccess from "@/access/checkAccess";

router.beforeEach(async (to, from, next) => {
  // console.log("登陆用户", store.state.user.loginUser);
  let loginUser = store.state.user.loginUser;
  // 自动登录
  if (
    !loginUser ||
    !loginUser.userRole ||
    loginUser.userRole === ACCESS_ENUM.NOT_LOGIN
  ) {
    const sessionUserAccount = sessionStorage.getItem("LoginUserAccount");
    const sessionUserRole = sessionStorage.getItem("LoginUserRole");
    const sessionUserId = sessionStorage.getItem("LoginUserId");
    await store.dispatch("user/getLoginUser", {
      userAccount: sessionUserAccount,
      userRole: sessionUserRole,
      userId: sessionUserId,
    });
    // console.log("我想赋值", store.state.user.loginUser);
    loginUser = store.state.user.loginUser;
  }
  const needAccess = (to.meta?.access as string) ?? ACCESS_ENUM.NOT_LOGIN;
  // console.log("需要的权限：", needAccess);
  if (needAccess !== ACCESS_ENUM.NOT_LOGIN) {
    // 要访问的页面需要登录才能访问
    if (
      !loginUser ||
      !loginUser.userRole ||
      loginUser.userRole === ACCESS_ENUM.NOT_LOGIN
    ) {
      next(`/user/login?redirect=${to.fullPath}`);
      return;
    }
    // 如果已经登录了但是权限不足
    if (!checkAccess(loginUser, needAccess)) {
      next("/noAuth");
      return;
    }
  }
  next();
});
